import { fetchEventSource, type EventSourceMessage } from "@microsoft/fetch-event-source"
import { useUserStore } from "@/stores/modules/UserStore"

type OnMessage = ((event: EventSourceMessage) => void) | undefined
type OnError = ((err: any) => (number | void | undefined | null)) | undefined
type OnClose = (() => void) | undefined
type Options = {
  onMessage?: OnMessage
  onError?: OnError
  onClose?: OnClose
}


export const useEventSource = <T extends object>(url: string, params: T, options: Options) => {
  const userStore = useUserStore()
  const controller = new AbortController()
  const { onMessage, onError, onClose } = options
  return fetchEventSource(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${userStore.token}`,
    },
    body: JSON.stringify(params),
    signal: controller.signal,
    openWhenHidden: true,
    onmessage: onMessage,
    onerror: onError,
    onclose: onClose,
  })
}
